import json
import logging

import numpy as np

from api.serial import sample, producer
from detecter import settings

logger = logging.getLogger('serial.sample')


# 封装返回数据
class SocketResponse:
    def __init__(self):
        # self.resp_dict = {'code': 0, 'msg': 'success', 'data': ''}
        self.resp_dict = {'code': 0, 'msg': 'success', 'data': ''}

    @classmethod
    def ok(cls, data='', msg=None):
        resp = SocketResponse()
        if msg:
            resp.resp_dict['msg'] = msg
        resp.resp_dict['data'] = data
        return json.dumps(resp.resp_dict, cls=sample.NpEncoder)

    @classmethod
    def error(cls, msg=None):
        logger.error(msg)
        resp = SocketResponse()
        resp.resp_dict['code'] = 500

        if msg:
            resp.resp_dict['msg'] = msg
        else:
            resp.resp_dict['msg'] = '未知异常,请联系管理员'
        return json.dumps(resp.resp_dict)

    def __str__(self):
        return json.dumps(self.resp_dict)


class SocketRequest:
    def __init__(self, request_json_str):
        self.req_str = request_json_str
        self.req_dict = json.loads(request_json_str)

    def __str__(self):
        return self.req_str

    def get_param(self, key):
        if key in self.req_dict:
            return self.req_dict[key]
        else:
            return None

    def set_param(self, key, value):
        if key in self.req_dict:
            origin = self.req_dict[key]
            self.req_dict[key] = value
            return origin
        else:
            self.req_dict[key] = value
            return None


class UIResult:
    result_choice = (
        (1, '品质正常'),
        (2, '不 良品'),
    )

    def __init__(self, id, made_no, result=1):
        self.made_no = made_no
        self.portrait_location = ''
        self.portrait_pressure = ''
        self.portrait_speed = ''
        # 设定压力曲线图 qkw 修改于20230216
        self.setting_pressure = ''
        # 设定速度曲线图 qkw 修改于20230315
        self.setting_speed = ''

        # 上下界曲线 qkw 修改于20220517
        self.shangjie_pressure = ''
        self.xiajie_pressure = ''
        self.shangjie_speed = ''
        self.xiajie_speed = ''
        # 正样本画像分段点
        self.portrait_seg_points = ''
        # 当前样本
        self.sample_location = ''
        self.sample_pressure = ''
        self.sample_speed = ''
        # 该样本各段置信度
        self.seg_list = ''
        # 该样本分段点
        self.sample_seg_points = ''
        # 异常率
        self.abnormal_rate = ''
        self.sample_id = id
        self.result = result  # 品质正常

        # zxy 修改于 20200109
        self.unassigned_count = ""  # 待聚类的负样本数量
        self.current_threshold = ""  # 当前样本用来判断的阈值
        # zxy 修改于 20200207
        self.min_samples_to_cluster = ""  # 运行聚类的最少样本数

    def set_result(self, flag=True):
        if flag:
            self.result = 1
        else:
            self.result = 2

    def set_portrait_info(self, portrait_list):
        # self.portrait_pressure = portrait_list[0]
        try:
            portrait_list_test = np.array(portrait_list[0])
            portrait_list_test = np.maximum(portrait_list_test, 0)
            self.portrait_pressure = [round(i, 2) for i in portrait_list_test]
        except:
            self.portrait_pressure = portrait_list[0]

        # self.portrait_location = portrait_list[1]
        try:
            self.portrait_location = [round(i, 2) for i in np.array(portrait_list[1])]
        except:
            self.portrait_location = portrait_list[1]

        # self.portrait_speed = portrait_list[2]
        try:
            self.portrait_speed = [round(i, 2) for i in np.array(portrait_list[2])]
        except:
            self.portrait_speed = portrait_list[2]

    def set_sample_info(self, sample_list):
        self.sample_pressure = sample_list[0]
        self.sample_location = sample_list[1]
        self.sample_speed = sample_list[2]

    def set_seg_list(self, seg_list):
        self.seg_list = seg_list

    def set_seg_points(self, portrait_seg_points):
        self.portrait_seg_points = portrait_seg_points

    def set_setting_pressure(self, sample_setting_pressure):
        try:
            self.setting_pressure = [round(i, 2) for i in np.array(sample_setting_pressure)]
        except:
            self.setting_pressure = []

    def set_setting_speed(self, sample_setting_speed):
        try:
            self.setting_speed = [round(i, 2) for i in np.array(sample_setting_speed)]
        except:
            self.setting_speed = []

    def set_detect_result(self, result):
        self.seg_list = result[0]  # 各段置信度
        # self.sample_pressure = result[1]  # 实际压力
        try:
            result_test = np.array(result[1])
            result_test = np.maximum(result_test, 0)  # 跟 0 比较  小于0 的  归为 0
            self.sample_pressure = [round(i, 2) for i in result_test]
        except:
            self.sample_pressure = result[1]
        # self.sample_location = result[2]  # 螺杆位置
        try:
            self.sample_location = [round(i, 2) for i in np.array(result[2])]
        except:
            self.sample_location = result[2]
        # self.sample_speed = result[3]  # 速度
        try:
            self.sample_speed = [round(i, 2) for i in np.array(result[3])]
        except:
            self.sample_speed = result[3]
        self.sample_seg_points = result[4]  # 分段点
        self.abnormal_rate = result[5]  # 总体置信度

    # zxy 修改于 20200109
    def set_unassigned_count(self, count):
        self.unassigned_count = count

    def set_current_threshold(self, threshold):
        self.current_threshold = threshold

    # qkw 修改于 20220519
    def set_shangxiajie_pressure1(self, shangjie_pressure, xiajie_pressure):
        # self.shangjie_pressure = shangjie_pressure
        try:
            shangjie_pressure_test = np.array(shangjie_pressure)
            shangjie_pressure_test = np.maximum(shangjie_pressure_test, 0)
            self.shangjie_pressure = [round(i, 2) for i in shangjie_pressure_test]
        except:
            self.shangjie_pressure = shangjie_pressure
        # self.xiajie_pressure = xiajie_pressure
        try:
            xiajie_pressure_test = np.array(xiajie_pressure)
            xiajie_pressure_test = np.maximum(xiajie_pressure_test, 0)
            self.xiajie_pressure = [round(i, 2) for i in xiajie_pressure_test]
        except:
            self.xiajie_pressure = xiajie_pressure

    def set_shangxiajie_speed(self, shangjie_speed, xiajie_speed):
        # self.shangjie_speed = shangjie_speed
        try:
            self.shangjie_speed = [round(i, 2) for i in np.array(shangjie_speed)]
        except:
            self.shangjie_speed = shangjie_speed
        # self.xiajie_speed = xiajie_speed
        try:
            self.xiajie_speed = [round(i, 2) for i in np.array(xiajie_speed)]
        except:
            self.xiajie_speed = xiajie_speed

    def get_info(self):
        return self.__dict__
